const util = require('../../utils/util.js')
const rate = wx.getSystemInfoSync().windowWidth / 750;

var  imgeUrl= 'https://oss.ztwlxx.cn/'
var resData = getApp().globalData.app_id == 'aQ%3D%3D' ? [imgeUrl + "1wmsexce小程序海报1(1).png", imgeUrl + "1wmsexce小程序海报2.png", imgeUrl + "1wmsexce小程序海报3.png", imgeUrl + "1wmsexcr海报4.png", imgeUrl + "11wmsexce海报5.png", imgeUrl + "1wmsexce海报6.png"] : [imgeUrl + "wm54sd4f分享海报1.png", imgeUrl + "wms5d5hf邀请海报2.png", imgeUrl + "wm25sdf分享海报3.png"];
function getImageInfo(url) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: url,
      success: resolve,
      fail: reject,
    })
  })
}

function canvasToTempFilePath(option, context) {
  return new Promise((resolve, reject) => {
    wx.canvasToTempFilePath({
      ...option,
      success: function (res) {
        resolve(res)
      },
      fail: reject,
    }, context)
  })
}
Component({
  
  properties: {
    sexesShow: Boolean,
    normalBtn: {
      type: String,
      value: '',
      observer: function (e) { }
    }

  },

  data: {
    imgUrl: getApp().globalData.imgUrl,
    imgUrls: getApp().globalData.imgUrls,
    isHua: false,
    resData,
    jumpIdx: 0,
    sexesShow: false,
    sharehaibao: false,
    imgUrls: getApp().globalData.imgUrls,
    openSettingshow: false,
    windowWidth: 496 * rate,
    windowHeight: 921 * rate,
    swiperIndex: `width:${496 * rate}px;height:${921 * rate}px`,
    swiperIndexN: `width:${356 * rate}px;height:${661 * rate}px`,
  },

  methods: {
    previewImage: function (e) {
      var current = e.target.dataset.src;
      var that = this
      wx.previewImage({
        current: current, // 当前显示图片的http链接
        urls: getimg()
      })

      function getimg() {
        var arrimage = []
        that.data.resData.map((item, index) => {
          arrimage.push(item)
        })
        return arrimage
      }
    },
    sexesShow() {
      this.setData({
        sexesShow: !this.data.sexesShow
      })
    },
    sharehaibao(nickName, cover) {
      this.setData({
        sharehaibao: !this.data.sharehaibao
      })
      if (!this.data.sharehaibao) {
        return false
      }
      if (this.data.isHua) {
        return false
      }
      wx.showLoading({
        title: '加载中...',
        mask:true
      })
     
      var that = this
      const avatarPromise = getImageInfo(cover)
      var promiseArr = this.data.resData.map(async function (req) {
        return getImageInfo(req)
      });
      promiseArr.push(util.utilUrl(`mid=${getApp().globalData.member_id}&type=3`))
      promiseArr.push(avatarPromise)
      Promise.all(promiseArr).then(function (respDataArr) {
   
        that.data.resData.map(function (req, index) {
          const ctx = wx.createCanvasContext(`myCanvas${index}`, that)
          ctx.fillStyle = "#FFFFFF";
          ctx.fillRect(0, 0, that.data.windowWidth, that.data.windowHeight);
          ctx.fill()
          var imageW = 80
          // 底图
          ctx.drawImage(
            respDataArr[index].path,
            0 * rate,
            0 * rate,
            that.data.windowWidth,
            that.data.windowHeight ,
          )
          // 太阳吗
          ctx.drawImage(
            respDataArr[promiseArr.length - 2].path,
            30 * rate,
            that.data.windowHeight - 200 * rate,
            150 * rate,
            150 * rate,
          )
          // 这是微信名
          ctx.setFontSize(rate * 28)
          ctx.setFillStyle('#FFF')
          ctx.setTextAlign('center');
          nickName.length > 8 ? nickName = nickName.slice(0, 7) + "..." : '';
          ctx.fillText(
            nickName,
            that.data.windowWidth / 2, rate * 140,
          )
          // 这是头像
          ctx.save();
          ctx.beginPath()
          ctx.arc(208 * rate + rate * imageW / 2, (20 + imageW / 2) * rate, imageW / 2 * rate, 0, 2 * Math.PI)
          ctx.clip()
          ctx.drawImage(
            respDataArr[promiseArr.length - 1].path,
            208 * rate,
            20 * rate,
            rate * imageW,
            rate * imageW,
          )
          ctx.restore();
          ctx.draw(false, () => {
            canvasToTempFilePath({
              canvasId: `myCanvas${index}`,  width: that.data.windowWidth, height: that.data.windowHeight
            }, that).then(
              ({
                tempFilePath
              }) => {
                var imageresData = 'resData[' + index + ']';
                that.setData({
                  [imageresData]: tempFilePath
                })
                getApp().globalData.shareImage = that.data.resData[that.data.jumpIdx]
              }
            )
          })
        });
        wx.hideLoading()
          that.setData({
            isHua: true
          })
        return '画图完成'
      }).catch(function (reason) {
        wx.hideLoading()
        console.log('promise reject failed reason', )
        wx.showModal({
          title: '提示',
          content: '生成图片中出错,请重试',
          showCancel: true,
          cancelText: '否',
          confirmText: '是',
          success: function(res) {
            that.setData({
              sharehaibao: false

            })
          },
        
        })
      })
        // .then(res => {
        //   console.log('画图完成')
        //   that.setData({
        //     isHua: true
        //   })

        // })
    },
    bindGetUserInfo(e) {
      var that = this
      if (e.detail.userInfo) {
        if (e.currentTarget.dataset.is) {
          that.setData({
            sexesShow: false,
            nick_name: e.detail.userInfo.nickName,
            cover: e.detail.userInfo.avatarUrl
          })
          that.sharehaibao(e.detail.userInfo.nickName, e.detail.userInfo.avatarUrl)
        } else {
          util.API('spwx/v1.Shop/fansCount', {}).then(res => {
            that.setData({
              fans: res.data
            })
            if (res.data.cha == 0) {
              util.API('spwx/v1.shop/user_list', {}).then(res => {
                let url = res.data.distribute_type == 0 ? "/pages/FenXiaoYuanShenQing/FenXiaoYuanShenQing" : "/pages/FenXiaoZhongXin/FenXiaoZhongXin"
                wx.navigateTo({
                  url,
                })
              })
              return false
            }
            that.setData({
              sexesShow: true,
              nick_name: e.detail.userInfo.nickName,
              cover: e.detail.userInfo.avatarUrl
            })
          })

        }
        util.API('wechat/authorize/updateapp', {
          nick_name: e.detail.userInfo.nickName,
          cover: e.detail.userInfo.avatarUrl,
        })

      }
    },
    bindGetUserInfos(e) {
      var that = this
      that.setData({
        sexesShow: false,
      })
    },

    bindchange(e) {
      this.setData({
        jumpIdx: e.detail.current
      })
      getApp().globalData.shareImage = this.data.resData[e.detail.current]
    },

    saveImage() {
      var that = this
      saveImageToPhotosAlbum({}, this).then(() => {
        wx.showToast({
          icon: 'none',
          title: '分享图片已保存至相册',
          duration: 2000,
        })
      }).catch(() => { })

      function saveImageToPhotosAlbum(option, pagethis) {
        return new Promise((resolve, reject) => {
          getImageInfo(getApp().globalData.shareImage).then((res) => {
            wx.saveImageToPhotosAlbum({
              filePath: res.path,
              success: resolve,
              fail: function (res) {
                that.setData({
                  openSettingshow: true
                })
              }
            })
          })
        })
      }
    },
    openSetting() {
      var that = this

      wx.openSetting({
        success(settingData) {
          if (settingData.authSetting['scope.writePhotosAlbum']) {
            that.saveImage()
          } else {
            wx.showModal({
              title: '提示',
              content: '获取权限失败,图片不能保存',
            })
          }
        }
      })
    },
  },
  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名

    attached: function () {
    
      var that = this
      wx.getSetting({
        success(settingData) {
          var settingDatais = settingData.authSetting['scope.writePhotosAlbum']
          if (settingDatais == false) {
            that.setData({
              openSettingshow: true
            })
          }
        }
      })
    },
    moved: function () { },
    detached: function () { },
  },
  pageLifetimes: {
    show: function () { },
    hide: function () { },
    resize: function (size) { }
  }
})